<?php

namespace App\Http\Models;

use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Encore\Admin\Facades\Admin;

class Goods extends BaseModel
{
    protected $table = 'goods';
    protected $guarded = [];
    const KILL = 2;
    const BURSTING = 1;
    protected $casts = [
        'copywriting' => 'json',
        'coverimage' => 'json',
    ];

    public function user()
    {
        return $this->hasOne('App\Http\Models\User', 'id', 'userid');
    }

    public function goodsshop()
    {
        return $this->hasOne(GoodsShop::class, 'gid', 'id');
    }

    public function goodkill()
    {
        return $this->hasOne(GoodsKill::class, 'gid', 'id');

    }

    public function goodscorrection()
    {
        return $this->hasOne(GoodsCorrection::class, 'gid', 'id');

    }

    public function goodkillinfo()
    {
        return $this->hasOne('App\Http\Models\GoodsKill', 'gid', 'id');

    }

    public function goodAudit()
    {
        return $this->hasOne('App\Http\Models\GoodsAudit', 'gid', 'id');

    }

    public function goodcoupon()
    {
        return $this->hasOne(GoodsCoupon::class, 'gid', 'id');

    }

    public function setCopywritingimageAttribute($pictures)
    {
        $index = ['first', 'second', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
        if (is_array($pictures)) {
            $new = [];
            for ($i = 0; $i < count($pictures); $i++) {
                $new[$index[$i]] = all_image_url($pictures[$i]);
            }
            $this->attributes['copywritingimage'] = json_encode($new, 320); // to_array_json($pictures, 'img');  // json_encode($pictures);
        }
    }


    public function getCopywritingimageAttribute($pictures)
    {

        $pictures = json_decode($pictures, true);
        if (is_null($pictures)) {
            $pictures = [];
        }
        return array_values($pictures);
        //return to_json_array($pictures);
    }


    public function setCoverimageAttribute($pictures)
    {

        if (is_array($pictures) && isset($pictures[0])) { //json_encode(["main" => $data['coverimage']])
            $this->attributes['coverimage'] = json_encode(["main" => all_image_url($pictures[0])], 320); //to_array_json($pictures, 'img');  // json_encode($pictures);
        } elseif (is_array($pictures) && isset($pictures['main'])) { //json_encode(["main" => $data['coverimage']])
            $this->attributes['coverimage'] = json_encode(["main" => all_image_url($pictures['main'])], 320); //to_array_json($pictures, 'img');  // json_encode($pictures);
        }
    }

    public function getCoverimageAttribute($pictures)
    {

        return json_decode($pictures, true);
        //return to_json_array($pictures);
    }

    public function setCopywritingAttribute($writing)
    {
        $index = ['first', 'second', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
        if (is_array($writing) && isset($writing[0])) {
            $new = [];
            for ($i = 0; $i < count($writing); $i++) {
                $new[$index[$i]] = $writing[$i];
            }
            $this->attributes['copywriting'] = json_encode($new, 320); // to_array_json($pictures, 'img');  // json_encode($pictures);
        } else {
            $this->attributes['copywriting'] = json_encode($writing, 320);
        }

    }

    public function getCopywritingAttribute($writing)
    {
        $writing = preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($writing));
        return $writing;
    }


    /**
     * 秒杀数据增加
     * @param $data  秒杀商品的信息
     * @param $taobaoinfo  从淘宝获得信息
     * @param $goodsid  商品id
     * @return bool
     */
    public static function addKillGood($data, $taobaoinfo, $goodsid, $gid = '')
    {

        if ($gid) {
            $goodinfo = self::where(['id' => $gid])->first();
            $coverimage = $goodinfo->coverimage;
            if (is_array($coverimage)) {
                array_shift($coverimage);
                array_unshift($coverimage, $data["coverimage"]);
            } else {
                $coverimage = [$data["coverimage"]];
            }
            unset($data["coverimage"]);
            // dd($coverimage);
            $goodinfo->goodstitle = $data['goodstitle'];
            $goodinfo->voucherprice = $data['voucherprice'];
            $goodinfo->commissionrate = $data['commissionrate'];
            $goodinfo->commissiontype = $data['commissiontype'];
            $goodinfo->goodslink = $data['goodslink'];
            $goodinfo->copywritingimage = [$data['copywritingimage']];
            $goodinfo->copywriting = [$data['copywriting']];  //json_encode(["first"=>$data['copywriting']],JSON_UNESCAPED_UNICODE);
            $goodinfo->coverimage = $coverimage;
            $goodinfo->userid = Auth::id();
            $goodinfo->goodsid = $goodsid;
            $goodinfo->goodstype = 2;
            $goodinfo->origprice = $taobaoinfo['zk_final_price'];
            $goodinfo->save();
            unset($data);
        } else {
            $goodinfo = new Goods();
            $goodinfo->coverimage = [$data["coverimage"]];
            $goodinfo->userid = Auth::id();
            $goodinfo->goodsid = $goodsid;
            $goodinfo->goodstype = 2;
            $goodinfo->origprice = $taobaoinfo['zk_final_price'];
            $goodinfo->goodstitle = $data['goodstitle'];
            $goodinfo->voucherprice = $data['voucherprice'];
            $goodinfo->commissionrate = $data['commissionrate'];
            $goodinfo->commissiontype = $data['commissiontype'];
            $goodinfo->goodslink = $data['goodslink'];
            $goodinfo->copywritingimage = [$data['copywritingimage']];
            $goodinfo->copywriting = [$data['copywriting']];//json_encode(["first"=>$data['copywriting']],JSON_UNESCAPED_UNICODE);
            $goodinfo->save();
            unset($data);
        }
        if ($goodinfo) {
            return $goodinfo->id;
        } else {
            return false;
        }

    }


    /**
     * 获取拒绝的原因
     */
    public static function getFailReason($goodstype = 0)
    {
        //3用户审核(平推),4用户审核(爆款)), 5秒杀描述,
        $_type = ($goodstype == 0) ? 3 : ($goodstype == 1 ? 4 : 5);  //转化搜索类型
        $res = DescribeRule::select('content')->where(['type' => $_type])->orderBy('id', 'asc')->get();
        if ($res) {
            $array = array_column($res->toArray(), 'content');
            array_unshift($array, '无');
            return $array;
        } else {
            return ['0' => '无'];
        }
        /*   return [
               '0' => '无',
               '1' => '佣金过低',
               '2' => '佣金未生效',
               '3' => '商品库存不足',
               '4' => '销售技术过低',
               '5' => '优惠券失效/无法领取/已领完/无法使用',
               '6' => '优惠券名带敏感词',
               '7' => '产品性价比低',
               '8' => '商品券后价格较高',
               '9' => '商品标题与商品详情不符',
               '10' => '其他',
           ];*/
    }

    public static function getFailReasonIndex($goodstype = 0, $refuse)
    {
        $refuse = json_decode($refuse, true);

        if (isset($refuse['content'])) {
            $refuse = $refuse['content'];
        } else {
            $refuse = '无';
        }
        $_type = ($goodstype == 0) ? 3 : ($goodstype == 1 ? 4 : 5);  //转化搜索类型
        $res = DescribeRule::select('content')->where(['type' => $_type])->orderBy('id', 'asc')->get();
        if ($res) {
            $array = array_column($res->toArray(), 'content');
            array_unshift($array, '无');
        }
        foreach ($array as $key => $value) {
            if ($value == $refuse) {
                return $key;
            }
        }

    }

    /**
     * 获取拒绝的原因
     */
    /*总分为20分，积分减为0时，将失去提交功能
    价格、佣金不对 扣3分
    主图不对 扣1分
    券名出现敏感词 扣1分
    标题描述与商品实情不符 扣1分
    预约时间不符 扣2分
    优惠券链接与商品不对应 扣3分
    恶意撬单 扣5分
    出现商家拉人短信、卡片 扣3分
    损害平台利益扣 20分
    其他 酌情扣分*/
    public static function getIntegral()
    {
        $res = DescribeRule::select('content')->where(['type' => 1])->orderBy('id', 'asc')->get();
        if ($res) {
            $array = array_column($res->toArray(), 'content');
            array_unshift($array, '无');
            return $array;
        } else {
            return ['0' => '无'];
        }
        /*return [
            '0' => '无',
            '1' => '不扣分--扣分(0分)',
            '2' => '价格,佣金不对--扣分(3分)',
            '3' => '主图不对--扣分(1分)',
            '4' => '劵名--扣分(1分)',
            '5' => '标题不对--扣分(1分)',
            '6' => '预约时间不符--扣分(2分)',
            '7' => '优惠券链接与商品对不住--扣分(3分)',
            '8' => '恶意翘单--扣分(5分)',
            '9' => '出现商家拉人短信,卡片--扣分(3分)',
            '10' => '损害平台利益--扣分(20分)',
            '11' => '其他',
        ];*/
    }


    /**
     * 获取拒绝的原因扣除的积分数
     */
    public static function getIntegralNumber()
    {
        $res = DescribeRule::select('num')->where(['type' => 1])->orderBy('id', 'asc')->get();
        if ($res) {
            $array = array_column($res->toArray(), 'num');
            array_unshift($array, '0');
            return $array;
        } else {
            return ['0' => '0'];
        }
        /*      return [
                  '0' => 0,//'无',
                  '1' => 0,//'不扣分',
                  '2' => 3,//'价格,佣金不对',
                  '3' => 1,//'主图不对',
                  '4' => 1,//'劵名',
                  '5' => 1,//'标题不对',
                  '6' => 2,//'预约时间不符',
                  '7' => 3,//'优惠券链接与商品对不住',
                  '8' => 5,//'恶意翘单',
                  '9' => 3,//'出现商家拉人短信,卡片',
                  '10' => 20,//'损害平台利益',
                  '11' => 0,// '其他',
              ];*/
    }

    /**
     * 获取淘宝的商品信息
     * @param $goodsId
     * @return mixed|\ResultSet|\SimpleXMLElement
     */
    public static function getTaobaoGoodsInfo($goodsId)
    {
        $c = new \TopClient;
        $c->appkey = env('TaoBao_App_Key');
        $c->secretKey = env('TaoBao_App_Secret');
        $req = new \TbkItemInfoGetRequest;
        $req->setNumIids($goodsId);
        $resp = $c->execute($req);
        return object_array($resp);
    }

    public static function getShopInfo($sell_name)
    {
        $c = new \TopClient;
        $c->appkey = env('TaoBao_App_Key');
        $c->secretKey = env('TaoBao_App_Secret');
        $req = new \ShopGetRequest;
        $req->setFields("sid,cid,title,nick,desc,bulletin,pic_path,created,modified,shop_score");
        $req->setNick($sell_name);
        $resp = $c->execute($req);
        return object_array($resp);
    }

    /**
     * 保存数据回调
     * 处理编辑主图 和二段文案图时修改一个时的bug
     */
    /*  public static function boot()
      {
          parent::boot();
          static::saving(function ($model) {
              if ($model->goodstype == self::BURSTING) {
                  if (!(isset($model->coverimage['img1']) && isset($model->coverimage['img2']))) {
                      $modelinfo = self::where(['id' => $model->id])->first();
                      if (isset($model->coverimage['img1'])) {
                          $image_array = $model->coverimage;
                          $image_array['img2'] = $modelinfo->coverimage['img2'];
                          $model->coverimage = $image_array;
                      } else {
                          $image_array = $model->coverimage;
                          $image_array['img1'] = $modelinfo->coverimage['img1'];
                          $model->coverimage = $image_array;
                      }
                  }
              }
          });
      }*/
    public static function getCategory()
    {
        $list = Cache::remember('category', 10, function () {
            return GoodsCategory::select('id', 'name')->where('pid', '0')->orderBy('ordid', 'asc')->get();
        });
        return $list;
    }


    /**
     * 写入审核日志
     * @param $goodsid  商品id
     * @param $goodsstate  商品状态 0未审 1一审通过 ,2终审通过  3退回 4下架
     * @param $content_index  打回原因下标
     * @param $integral_index  扣分原因下标
     * @param $userid   该商品属于的用户
     * @param $goods_type   该商品类型  //0平推单，1爆款单，2秒杀单
     */
    public static function save_log($goodsid, $goodsstate, $content_index, $integral_index, $old_status = 0, $fail_reason = '', $operation_type = 1)
    {
        $goods_info = Goods::where(['id' => $goodsid])->first();
        $userid = $goods_info->userid;
        $goods_type = $goods_info->goodstype;
        DB::beginTransaction();
        if ($goodsstate == 3) {
            $fail_content = Goods::getFailReason($goods_type)[$content_index];
            if (strpos($fail_content, '自定义') !== false && $fail_reason) {
                $fail_content = $fail_reason;
            } else {
                $fail_content = Goods::getFailReason($goods_type)[$content_index];
            }

        } else {
            $fail_content = '';
        }
        $goods_audit = GoodsAudit::addLog($goodsid, Admin::user()->id, $goodsstate, $fail_content);
        $user_integral_bool = true;

        if ($goodsstate == 3) {
            $integral_content = Goods::getIntegral()[$integral_index];
            $integral = Goods::getIntegralNumber()[$integral_index];
            if ($integral > 0) {
                $content_info = '【' . $goods_info->goodstitle . '】,因该商品:' . $integral_content;
                $user_integral_bool = UserCapital::addUserIntegral($userid, $integral, 0, $content_info, $goodsid, $integral_content);
            }
        }
        //检测商品是否存在机器上架的,如果存在直接下架之前机器采集的商品
        if ($goodsstate == 2) {
            $oldgoods = Goods::where(['goodsid' => $goods_info->goodsid, 'goodsstate' => 2])->where('userid', '<', 10000)->first();
            if ($oldgoods) {
                $oldgoods->goodsstate = 11;
                $old = $oldgoods->save();
                if ($old) {
                    StatisticsGoodsInfo::updateStatisticsGoods($oldgoods->id, $oldgoods->goodstype, 11, 1, $oldgoods->created_at, 2, false, 1);
                }
            }
        }
        /*  //增加今日统计
          $static_tody = StatisticsGoodsToday::updateTodayNumber($goodsstate, $goods_type, $goods_info->created_at);
          //爆款,秒杀,平推统计
          StatisticsGoods::updateStatisticsGoods($goods_type, $goodsstate);
          //统计用户在线商品状态
          StatisticsUserKill::addUserOnlineGood($userid, $goodsstate);
          //增加个人用户在线秒杀商品
          if ($goods_type == 2) {
              StatisticsUserKill::updateUserKill($userid, $goodsstate);
          }*/
        $static = StatisticsGoodsInfo::updateStatisticsGoods($goodsid, $goods_type, $goodsstate, $operation_type, $goods_info->created_at, $old_status);
        $good_bool = true;
        $user_capital = true;
        if ($goodsstate == 3) {  //修改拒绝原因
            $refuse = json_encode([
                "uid" => $userid,
                "time" => date('Y-m-d H:i:s', time()),
                "content" => $fail_content
            ], JSON_UNESCAPED_UNICODE);
            if ($goods_type == 1) {
                $voucher_number = env('Voucher_Fire_Deduct');
                $content = '爆款商品[' . $goods_info->goodstitle . ']审核被拒,退回' . $voucher_number . '点券';
            } elseif ($goods_type == 2) {
                $voucher_number = env('Voucher_Kill_Deduct');
                $content = '秒杀商品[' . $goods_info->goodstitle . ']审核被拒,退回' . env('Voucher_Kill_Deduct') . '点券';
            } else {
                $voucher_number = env('Voucher_Normal_Deduct');
                $content = '平推商品[' . $goods_info->goodstitle . ']审核被拒,退回' . env('Voucher_Normal_Deduct') . '点券';
            }
            $user_capital = UserCapital::addUserCapital($userid, $voucher_number, 1, $content, $goodsid, $fail_content);
            $good_bool = Goods::where(['id' => $goodsid])->update(['refuse' => $refuse]);
        }
        if (in_array($goodsstate, [2, 3])) {
            self::updateStatusTime($goodsid);
        }
        if ($goods_audit && $user_integral_bool && $user_capital && $good_bool && $static) {
            DB::commit();
            return true;
        } else {
            DB::rollBack();
            return false;
        }
    }

    /**
     * 更新商品审核的状态值
     * @param $goodsid 商品id
     * @param $site_error_status 0,1
     */
    public static function updateError($goodsid, $site_error_status)
    {
        $model = self::where(['id' => $goodsid])->first();
        if ($model) {
            $model->site_error_status = $site_error_status;
            $model->auto_error_status = $site_error_status;
            if ($model->goodsstate == 9) {
                $model->goodsstate = 2;
                $model->status_time = date('Y-m-d', time());
                $bool = $model->save();
                if ($bool) {
                    $bool = StatisticsGoodsInfo::updateStatisticsGoods($goodsid, $model->goodstype, 2, 1, $model->created_at, 9, false);
                }
            } else {
                $bool = $model->save();
            }
            return $bool;
        } else {
            return false;
        }
    }

    /**
     * 获取编辑的商品类型
     * @param $goodsId
     * @param $http_refer
     * @return array
     */
    public static function getGoodsType($goodsId, $http_refer)
    {
        preg_match_all("/(?<=(\?|&)type=)\w+/i", $http_refer, $match);
        $goods = Goods::where(['id' => $goodsId])->first();
        $is_error = ($goods->site_error_status || $goods->auto_error_status) ? true : false;
        if (empty($http_refer)) {
            //1,all_allow  通过 2,refuse 拒绝,3 未审核  ,4 lower 下架
            $type = $goods->goodsstate == 2 ? 1 : ($goods->goodsstate == 0 ? 3 : ($goods->goodsstate == 3 ? 2 : 4));
        } elseif (!isset($match[0][0])) {
            $type = $goods->goodsstate == 2 ? 1 : ($goods->goodsstate == 0 ? 3 : ($goods->goodsstate == 3 ? 2 : 4));
        } else {
            $type = !isset($match[0][0]) ? 3 : ($match[0][0] == 'all_allow' ? 1 : ($match[0][0] == 'refuse' ? 2 : 4));
        }
        if ($is_error && $goods->goodsstate == 2) {
            $goods->goodsstate = 9;
            $goods->save();
        }
        return ['is_error' => $is_error, 'type' => $type, 'goodsstate' => $goods->goodsstate];
    }

    public static function addErrorInfo($error_id, $gid)
    {
        if ($error_id) {
            $goods = Goods::where(['id' => $gid])->first();
            if (!($goods->site_error_status && $goods->auto_error_status)) {
                $goods->site_error_status = 1;
                $goods->auto_error_status = 1;
                $goods->save();
            }
        }
        return true;
    }

    public static function updateStatusTime($gid)
    {
        $Onegoods = Goods::where(['id' => $gid])->first();
        $Onegoods->status_time = date('Y-m-d H:i:s', time());
        return $Onegoods->save();
    }
}